﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Threading.Tasks;
using Wicresoft.Logger;
using Wicresoft.Message.Entity;

namespace Wicresoft.Task.Common
{
    public class EmailSender : Wicresoft.Task.Common.IntervalTask
    {
        protected override void Execute()
        {
            using (var dc = new EmailContext())
            {
                Parallel.ForEach(dc.Emails.Where(p => !p.IsSent), p =>
                {
                    try
                    {
                        //
                        SendEmailInternal(p);
                        //
                        p.IsSent = true;
                        p.SentTime = DateTime.Now;
                        Log.Info(this.Name, "Email [{0}] has been sent and is about to be marked as sent.", p.Subject);
                    }
                    catch (Exception e)
                    {
                        Log.Exception(this.Name, e);
                    }
                });

                try
                {
                    int n = dc.SaveChanges();
                    if (n > 0)
                        Log.Info(this.Name, "{0} email(s) have been sent and saved.", n);
                }
                catch (Exception e)
                {
                    Log.Exception(this.Name, e);
                }
            }
        }

        private void SendEmailInternal(Email mail)
        {
            MailMessage msg = new MailMessage();

            msg.From = new MailAddress(mail.From);

            foreach (var r in mail.To.Split(';'))
            {
                if (r.Contains('@'))
                    msg.To.Add(r);
            }

            if (mail.Cc != null)
                foreach (var r in mail.Cc.Split(';'))
                {
                    if (r.Contains('@'))
                        msg.CC.Add(r);
                }

            if (mail.Bcc != null)
                foreach (var r in mail.Bcc.Split(';'))
                {
                    if (r.Contains('@'))
                        msg.Bcc.Add(r);
                }

            if (mail.ReplyTo != null)
                foreach (var r in mail.ReplyTo.Split(';'))
                {
                    if (r.Contains('@'))
                        msg.ReplyToList.Add(r);
                }

            msg.SubjectEncoding = Encoding.UTF8;
            msg.Subject = mail.Subject;

            msg.BodyEncoding = Encoding.UTF8;
            msg.IsBodyHtml = true;
            msg.Body = mail.Body;

            using (SmtpClient sc = new SmtpClient(Bag.SmtpServer))
            {
                sc.Send(msg);
            }
        }
    }
}
